<script>
import api from '@/api'

export default {
  name: 'index',
  data() {
    return {
      // 当前tab选中的位置，默认选中中间的位置
      tabPosition: 1,
      // 当前用户的昵称
      nickname: '',
      // 当前用户的头像
      avatar: 'https://www.dingxians.cn/upload/images/user/avatar.png',
      // 刷新状态
      isRefreshing: false,
      // 当前页码
      page: 1,
      // 尾页
      lastPage: 2,
      // 创建的红包信息
      packet: {
        // 红包标题
        title: '',
        // 红包数量
        num: '',
        // 红包金额
        amount: '',
      },
      // 红包列表
      packetList: [],
      tabList: [
        {
          id: 0,
          title: '创建红包'
        },
        {
          id: 1,
          title: '领取红包'
        },
        {
          id: 2,
          title: '领取记录'
        }
      ]
    }
  },
  watch: {
    // 侦听tab选中的变化，即立即刷新
    tabPosition(val) {
      // 创建红包页面不需要加载
      if (val === 0) return
      if (this.isRefreshing) {
        this.isRefreshing = false
      }
      // 解决刷新问题
      this.$nextTick(() => {
        this.isRefreshing = true
      })
    },
  },
  computed: {
    // 按钮文字
    btnStr() {
      return this.tabPosition === 1 ? '领取红包' : '已领取'
    },
    // 是否可以下拉刷新
    refreshEnabled() {
      return this.tabPosition > 0
    },
  },
  onLoad() {
    // 获取当前的用户信息
    const avatar = uni.getStorageSync('avatar')
    const nickname = uni.getStorageSync('nickname')

    if (avatar) {
      this.avatar = avatar
    }
    this.nickname = nickname
    this.$nextTick(() => {
      this.isRefreshing = true
    })
  },
  // 每次显示时都刷新数据，保持数据是最新的
  onShow() {
    // 创建红包页面不需要加载
    /*if (this.tabPosition === 0) {
      return
    }*/
    // 刷新数据
  },
  methods: {
    // 点击之后进入红包详情页领取红包
    openPacket(id) {
      // 领取记录不能跳转
      if (this.tabPosition === 2) return
      this.header('/packageA/packet/detail?id=' + id, 1, true)
    },
    // 下拉刷新回调
    onRefresh() {
      // 重置的最初状态，执行刷新重新获取数据
      this.page = 1
      this.lastPage = 1
      this.isRefreshing = true
      this.packetList = []
      this.getPacketList()
    },
    // 上拉加载更多
    onLoadMore() {
      // 当前页码和尾页相同时，停止加载更多数据
      if (this.page >= this.lastPage) return
      this.page++
      this.getPacketList()
    },
    // 创建红包主要实现
    async createPacket() {
      try {
        await uni.showLoading()
        const result = await api.redPackets.create({
          ...this.packet,
        })
        if (result.code === 200) {
          // 充值填写的红包信息
          Object.assign(this.packet, {
            title: '',
            num: '',
            amount: '',
          })
          return await uni.showToast({ title: result.msg || '红包创建成功', icon: 'success' })
        }
        // 状态码不为200视为失败
        throw new Error(result.msg || '创建失败')
      } catch (e) {
        await uni.showToast({ icon: 'none', title: e.message })
      } finally {
        uni.hideLoading()
      }
    },
    // 获取红包列表和领取记录
    async getPacketList() {
      const position = this.tabPosition
      try {
        let result
        if (position === 1) {
          // 红包列表
          result = await api.redPackets.index({
            page: this.page,
            /*limit: 6,*/
          })
        } else {
          // 领取记录
          result = await api.redPackets.record({
            page: this.page,
            /*limit: 6,*/
          })
        }
        // 判断当前请求的红包列表是否是当前tab选项卡
        if (position !== this.tabPosition) return
        if (result.code === 200) {
          // 设置尾页
          this.lastPage = result.data.last_page
          // 追加内容
          this.packetList.push(...result.data.data)
        }
      } catch (e) {
        if (this.page === 1)
          this.packetList = []
      } finally {
        this.isRefreshing = false
      }
    },
  },
}
</script>

<template>
  <!-- 红包页面 -->
  <view class="packet-layout">
    <my-header title="潮玩红包"></my-header>
    <my-content class="packet-content">
      <my-tab v-model="tabPosition" :tab-list="tabList"></my-tab>
      <!--   创建红包页面   -->
      <template v-if="tabPosition === 0">
        <view class="packet-create">
<!--          <view class="packet-create-user">
            <view class="packet-create-user-bg">
              <image class="packet-create-user-avatar" :src="avatar"></image>
            </view>
            <text class="packet-create-username">{{ nickname }}</text>
            <text class="packet-create-homeowner">房主</text>
          </view>-->
          <view class="packet-create-form">
            <view class="packet-create-form-item">
              <text class="packet-create-label">主题：</text>
              <input type="text" placeholder="请输入红包主题" v-model="packet.title">
            </view>
            <view class="packet-create-form-item">
              <text class="packet-create-label">数量：</text>
              <input type="number" placeholder="请输入红包数量(10-50)" v-model="packet.num">
            </view>
            <view class="packet-create-form-item">
              <text class="packet-create-label">金额：</text>
              <input type="digit" placeholder="请输入红包金额" v-model="packet.amount">
            </view>
          </view>
        </view>
        <view class="packet-create-btn btn-primary" @click="createPacket">创建红包</view>
      </template>
      <!--   红包列表   -->
      <scroll-view v-else scroll-y="true" class="packet-scroll-view" :refresher-enabled="refreshEnabled"
                   :refresher-triggered="isRefreshing"
                   refresher-background=""
                   @refresherrefresh="onRefresh"
                   @scrolltolower="onLoadMore">
        <view class="packet-list">
          <my-packet @click.native="openPacket(packet.id)" v-for="packet in packetList" :key="packet.id"
                     :btn-str="btnStr"
                     :disabled="tabPosition === 2" :packet="packet">
          </my-packet>
        </view>
      </scroll-view>
    </my-content>
  </view>
</template>

<style scoped lang="scss">
.packet-layout {
  height: 100vh;
  background-color: #141414;

  .packet-content {
    height: 100%;
    width: 100%;
    display: flex;
    flex-direction: column;

    .packet-create {
      width: 710rpx;
      height: 425rpx;
      margin: 20rpx auto;
      background-image: url("https://www.dingxians.cn/upload/images/packet/panel-bg.png");
      background-size: 100% 100%;
      overflow-y: hidden;
      color: white;

      .packet-create-user {
        display: flex;
        justify-content: center;
        align-items: center;
        margin-top: 42rpx;

        .packet-create-user-bg {
          /*width: 106rpx;
          height: 106rpx;
          display: flex;
          align-items: center;
          justify-content: center;
          background-image: url("https://www.dingxians.cn/upload/images/common/icon-border.png");
          background-size: 100% 100%;*/

          .packet-create-user-avatar {
            width: 82rpx;
            height: 82rpx;
            border: 2rpx solid #dd524d;
            border-radius: 50%;
          }
        }

        .packet-create-username {
          font-size: 32rpx;
          font-weight: bold;
          margin-left: 16rpx;
          max-width: 300rpx;
          text-overflow: ellipsis;
          white-space: nowrap;
          overflow: hidden;
        }

        .packet-create-homeowner {
          background-color: #dd524d;
          font-size: 22rpx;
          color: #141414;
          padding: 3rpx 6rpx;
          font-weight: bold;
          margin-left: 8rpx;
        }

      }

      .packet-create-form {
        margin: 50rpx 32rpx 0;

        .packet-create-form-item {
          display: flex;
          padding: 24rpx 0;
          border-bottom: 2rpx solid #F8F9FC;

          .packet-create-label {
            font-size: 32rpx;
            font-weight: bold;
          }
        }
      }
    }

    .packet-create-btn {
      margin: 42rpx auto;
      width: 610rpx;
      height: 80rpx;
      text-align: center;
      line-height: 80rpx;
      color: white;
      font-size: 32rpx;
      font-weight: bold;
    }

    .packet-scroll-view {
      width: 710rpx;
      margin: 0 auto;
      flex: 1;
      overflow-y: hidden;

      .packet-list {
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;
      }
    }
  }
}

/* 二改代码 */
</style>